var globalSocket;
$(function() {
	if (typeof (WebSocket) == "undefined") {
		console.log("您的浏览器不支持WebSocket");
	} else {
		var uid = $("input[name='hideId']").val();
		if (!(uid)) {
			uid = "GUEST_" + Math.random();
		}
		var socketUrl = commentWebSocketUrl + "/webSocket/" + uid;
		if (globalSocket != null) {
			globalSocket.close();
			globalSocket = null;
		}
		globalSocket = new WebSocket(socketUrl);
		// 打开事件
		globalSocket.onopen = function() {
			sessionStorage.setItem("globalSocketStatus", true);
			console.log("websocket已打开");
		};
		// 获得消息事件
		globalSocket.onmessage = function(msg) {
			analysisMsg(msg);
			// 发现消息进入 开始处理前端触发逻辑
		};
		// 关闭事件
		globalSocket.onclose = function() {
			sessionStorage.setItem("globalSocketStatus", false);
			console.log("websocket已关闭");
		};
		// 发生了错误事件
		globalSocket.onerror = function() {
			sessionStorage.setItem("globalSocketStatus", false);
			console.log("websocket发生了错误");
		}
		window.onbeforeunload = function(event) {
			sessionStorage.setItem("globalSocketStatus", false);
		};
	}
});

function analysisMsg(msg) {
	var data = JSON.parse(msg.data);
	switch (data.code) {
	case 0:
		var serverMsg = "收到服务端信息：" + data.msg;
		console.log(serverMsg);
		break;
	case 600:
		utils.postUrl("/refreshMenu", {}, function(res) {
		});
	case 601:
		utils.postUrl("/refreshPermission", {}, function(res) {
		});
	default:
		break;
	}
}

function sendMessage(msg) {
	if (typeof (WebSocket) == "undefined") {
		console.log("您的浏览器不支持WebSocket");
	} else {
		console.log(msg);
		globalSocket.send(msg);
	}
}